<!--
 * @Descripttion: 客户导入导出
 * @version: V1.0
 * @Author: GaoWei
 * @Date: 2021-06-17 15:49:11
 * @LastEditors: GW
 * @LastEditTime: 2021-12-01 15:08:28
-->
<template>
    <div>
        <!-- 导入：步骤1 -->
            <a-modal v-model="importVisible" :title="'导入'+ dataSourceName" centered on-ok="handleok" width="650px">
                <div style="margin-left:30px;">
                    <p>
                        第1步：下载{{dataSourceName}}导入模板
                        <a href="javascript:;" @click="downloadTemplate" style="font-size: 12px;color: blue;">点击下载模板</a>
                    </p>
                    <p>
                        第2步：<sapn style="color:red;">*</sapn>上传文档
                        <label>
                            <input type="file" id="bbq_file" name="file" style="padding-left: 15px;" class="form-file" />
                        </label>
                    </p>
                    <div>
                        <span>第3步：导入资料至</span>
                        <label style="padding-left: 15px;">
                            <input name="Fruit" type="radio" checked />{{dataSourceName}}
                        </label>
                    </div>
                    <div style="margin-top: 15px;">
                        <p>导入说明</p>
                        <p>1.上传存储有{{dataSourceName}}的Excel文件，大小不超过5M</p>
                        <p>2.设置Excel里的列与系统中的列的对应关系</p>
                        <div v-if="source == 'crm'">
                            <p>3.如果{{dataSourceName}}名称已存在，则将联系人信息追加到此{{dataSourceName}}的联系人后面</p>
                            <p>4.开始导入</p>
                        </div>
                        <div v-else>
                             <p>3.开始导入</p>
                        </div>
                        
                    </div>
                    <div style="margin-top: 25px;">
                        <p>
                            <sapn style="color:red;">*</sapn>'所属地区'栏目格式说明
                        </p>
                        <p>1.可以传入省市区的组合(例：a.四川省 b.四川省/成都市 c.四川省/成都市/锦江区 )</p>
                        地区助手：
                        <a-cascader placeholder="请选择地区" change-on-select show-search :field-names="{ label: 'areaName', value: 'areaCode',children: 'children'}" @change="onAreaChange" :options="regions" />
                        '所属地区'：<sapn style="color:red;">{{ areaText }}</sapn>
                    </div>
                </div>
                <template slot="footer">
                    <a-button key="submit" type="primary" @click="importCrm">下一步</a-button>
                    <a-button key="back" @click="() => (importVisible = false)">取消</a-button>
                </template>
            </a-modal>
            <!-- 导入：步骤2 -->
            <a-modal v-model="filedVisible" title="匹配导入字段" centered on-ok="handleok" width="650px">
                <a-spin :spinning="isSpinning" tip="导入中...">
                    <div style="margin-left:30px;height: 400px;overflow-y: scroll;">
                        <a-table :columns="filedColumns" :data-source="filedData" :pagination="false" bordered>
                            <template slot="crmFiled" slot-scope="text, record, index">
                                <select-group title="下拉效果" size="small" selectStyle="width:80%;" labelStyle="display: none;" :dataList="text"  v-model="record.crmCode"></select-group>
                            </template>
                        </a-table>
                    </div>
                </a-spin>

                <template slot="footer">
                    <a-button v-show="!isSpinning" key="submit" type="primary" @click="importData">导入</a-button>
                    <a-button v-show="!isSpinning" key="back" @click="() => (filedVisible = false)">取消</a-button>
                </template>
            </a-modal>
             <!-- 导入：步骤3 -->
            <a-modal v-model="resultVisible" title="导入结果" centered on-ok="handleok" width="650px">
                <div style="margin-left:30px;height: 200px;overflow-y: scroll;">
                    <p>新增客户数：{{impotrResult.insertCustomerNum || 0}}</p>
                    <p>更新客户数：{{impotrResult.updateCustomerNum || 0}}</p>
                    <p>客户导入失败数：{{impotrResult.failNum || 0}}</p>
                    <p>联系人导入成功数：{{impotrResult.linkManNum || 0}}</p>
                    <p v-show="importType=='task'">外呼任务明细导入成功数：{{impotrResult.taskDetailNum}}</p>
                    <p>如果您需要导入失败的记录及原因，请点击下载按钮</p>
                </div>
                <template slot="footer">
                    <a-button key="submit" type="primary" icon="download" @click="downloadImportResult">下载</a-button>
                    <a-button key="back" @click="() => (resultVisible = false)" icon="close">取消</a-button>
                </template>
            </a-modal>
            <!-- 导出 -->
            <a-modal v-model="exportVisible" :title="'导出' + dataSourceName + '数据文件'" centered on-ok="handleok" width="650px">
                <div style="margin-left:30px;height: 200px;overflow-y: scroll;">
                    <a-radio-group v-model="exportRadioValue">
                        <p>
                            <a-radio value="1">导出所选{{dataSourceName}}：{{exportSelectData.exportValue || 0}}条</a-radio>
                        </p>
                        <p>
                            <a-radio value="2">导出符合条件{{dataSourceName}}：{{pagination.total || 0}}条</a-radio>
                        </p>
                    </a-radio-group>
                </div>
                <template slot="footer">
                    <a-button key="submit" type="primary" icon="download" @click="exportCrmData">导出</a-button>
                    <a-button key="back" @click="() => (exportVisible = false)" icon="close">取消</a-button>
                </template>
            </a-modal>
    </div>
</template>

<script>
import {
    exportData,
    importTemplate,
    getExcelFiled,
    importData,
    downloadFailCause
} from "@/api/crm/customer";
import {areaPageListToTreeForId } from "@/utils/tree";
import { treeList } from "@/api/area";

export default {
    props: {
        importType:{
            type: String,
            default: 'crm'
        },
        source: {
            type: String,
            default: 'crm'
        },
        companyType: {
            type: String,
            default: 'isCustomer'
        },
        templateName:{
            type: String,
            default: '数据导入模板'
        },
        dataSourceName:{
            type: String,
            default: ''
        },
        pagination:{
            type:Object,
        },
        postData:{
            type:Object,
        },
        onOffDefineFields:{
            type:Object,
        },
        exportSelectData:{
            type:Object,
        },
        selectedKeys:{
           type:Object,  
        },
      
    },
    data() {
        const filedColumns = [
            {
                title: "Excel字段",
                dataIndex: "excelFiled",
                key: "excelFiled",
                align: "left"
            },
            {
                title: "系统字段",
                dataIndex: "crmFiled",
                key: "crmFiled",
                align: "left",
                scopedSlots: { customRender: "crmFiled" }
            }
        ];
        //表格 头部 可伸缩
        return {
            importVisible: false, //导入文件弹窗
            filedVisible: false, //字段匹配弹窗
            resultVisible: false, //导入结果弹窗
            excelFiled: [], //excel字段
            impotrResult: {}, //导入结果
            isSpinning: false, //导入加载框
            exportVisible: false, //导出弹窗
            exportRadioValue: "1", //导出redio值
            filedColumns,
            filedData: [],
             //行政区信息
            regions: [],
            //选择地区
            areaText: '',
            moreFormData: null
        };
    },
    mounted() {
        this.areaTree();
    },
    updated() {
     
    },
    computed: {
    
    },
    methods: {
        //地区选择事件
        onAreaChange(value, selectedOptions) {
            this.areaText = selectedOptions.map(o => o.areaName).join('/');
        },
        //加载 区域数据
        areaTree() {
            treeList()
                .then(response => {
                    if (response.code === 200) {
                        const { data } = response;
                        const childrenNav = [];
                        areaPageListToTreeForId(data, childrenNav, 0);
                        console.log("加载 区域数据:", childrenNav);
                        this.regions = childrenNav;
                    }
                })
                .catch(error => { });

        },
        //导出供应商数据
        exportCrmData () {
            const { postData, onOffDefineFields,dataSourceName } = this;
            console.log(dataSourceName + "系统——搜索条件：", onOffDefineFields);
            postData.dtos = onOffDefineFields;
            if (this.exportRadioValue == 1) {
                if (this.exportSelectData.exportValue == 0) {
                    this.$message.warn("请选择要导出的" + dataSourceName);
                    return false;
                }
                postData.crmIds = this.selectedKeys;
            } else {
                if (this.pagination.total == 0) {
                    this.$message.warn("没有"+dataSourceName+"数据不能导出");
                    return false;
                }
                postData.crmIds = null;
            }
            exportData(postData).then(response => {
                let url = window.URL.createObjectURL(
                    new Blob([response], { type: "application/vnd.ms-excel" })
                );
                let link = document.createElement("a");
                link.style.display = "none";
                link.href = url;
                link.setAttribute("download", dataSourceName + "资料.xls");
                document.body.appendChild(link);
                link.click();
                this.resultVisible = false;
                this.exportVisible = false;
                this.selectedKeys = [];
            });
        },
        //导入
        importCrm () {
            const { dataSourceName } = this;
            //上传execl文件 匹配字段
            //this.$refs["merge-modal"].show();
            const formData = new FormData();
            let excelFile = document.getElementById("bbq_file").files[0];
            if (excelFile == null || excelFile.name == "") {
                this.$error({
                    title: "错误提示",
                    content: "文件不能为空"
                });
                return false;
            }

            var AllImgExt = ".xls|.xlsx|";
            var extName = excelFile.name
                .substring(excelFile.name.lastIndexOf("."))
                .toLowerCase();
            if (AllImgExt.indexOf(extName + "|") == -1) {
                this.$error({
                    title: "错误提示",
                    content: "文件格式错误，请上传xls、xxlsx类型文件"
                });
                return false;
            }

            let size = excelFile.size;
            size = size / (1024 * 1024);
            if (size >= 5) {
                this.$error({
                    title: "错误提示",
                    content: "文件过大,不能超过5M"
                });
                return;
            }
           
            
            formData.append("file", excelFile);
            formData.append("source", this.source);
            getExcelFiled(formData).then(response => {
                if (response.code == 200) {
                    this.importVisible = false;
                    let exlFiled = response.data.excelFiled;
                    if (exlFiled == null || exlFiled.length == 0) {
                        this.$error({
                            title: "错误提示",
                            content: "文件没有数据"
                        });
                        return;
                    }
                    this.filedVisible = true;
                    this.filedModelFooter = true;
                    this.excelFiled = exlFiled;
                    let crmFiled = response.data.crmFiled;
                    let cFiled = [];
                    let lFiled = [];
                    let tableFiledData = [];
                    cFiled.push({ key: '', title: '  ' });
                    for (let i = 0; i < crmFiled.length; i++) {
                        if (crmFiled[i].title.includes("联系人.")) {
                            lFiled.push(crmFiled[i]);
                        } else {
                            cFiled.push(crmFiled[i]);
                        }
                    }

                    console.log("获取表头", exlFiled);
                    for (let i = 0; i < exlFiled.length; i++) {
                        let item = crmFiled.find(f => f.title == exlFiled[i]);
                        console.log("匹配到的系统字段：",exlFiled[i],item)
                        tableFiledData.push({
                            excelFiled: exlFiled[i],
                            crmFiled: [
                                { groupTitle:  dataSourceName + "资料", data: cFiled },
                                { groupTitle: "联系人资料", data: lFiled }
                            ],
                            crmCode: item && item.key
                        });
                    }
                    console.log("filedData",tableFiledData)
                     this.filedData = tableFiledData;
                  
                }
            });
        },
        //下载模版
        downloadTemplate () {
            const {source} = this;
            importTemplate({source}).then(response => {
                let url = window.URL.createObjectURL(
                    new Blob([response], { type: "application/vnd.ms-excel" })
                );
                let link = document.createElement("a");
                link.style.display = "none";
                link.href = url;
                link.setAttribute("download", this.templateName);
                document.body.appendChild(link);
                link.click();
            });
        },
        //导入数据
        importData () {
            let { moreFormData } = this;
            this.isSpinning = true;
            this.filedModelFooter = false;
            let crmCodes = this.filedData.map(f => f.crmCode);
            console.log(crmCodes);
            const formData = new FormData();
            formData.append("file", document.getElementById("bbq_file").files[0]);
            formData.append("excelFiled", this.excelFiled);
            formData.append("dbFiled", crmCodes);
            formData.append("companyType", this.companyType);
             if(moreFormData){
                for (let key in moreFormData) {
                    formData.append(key, moreFormData[key]);
                }
            }
            importData(formData).then(response => {
                if (response.code == 200) {
                    this.impotrResult = response.data;
                    this.resultVisible = true;
                    this.filedVisible = false;
                    this.isSpinning = false;
                       //刷新父组件数据
                    this.$emit('syncFun');
                } else {
                    this.filedVisible = false;
                    this.isSpinning = false;
                    this.$message.error("导入失败，请联系管理员");
                }
            });
        },
        //下载导入结果
        downloadImportResult () {
            console.log("下载导入结果", this.impotrResult);
            const formData = new FormData();
            formData.append("excelField", this.impotrResult.excelField);
            formData.append("failCause", this.impotrResult.failCause);
            formData.append("failData", JSON.stringify(this.impotrResult.failData));
            downloadFailCause(formData).then(response => {
                let url = window.URL.createObjectURL(
                    new Blob([response], { type: "application/vnd.ms-excel" })
                );
                let link = document.createElement("a");
                link.style.display = "none";
                link.href = url;
                link.setAttribute("download", "导入失败的数据和原因.xls");
                document.body.appendChild(link);
                link.click();
                this.resultVisible = false;
            });
        },
        //导入弹窗
        importFile (data) {
             console.log("____________ w d __________________");
            if( typeof data == 'object'){
                Object.assign(this,data);
                console.log("____________importFile=>moreFormData __________________",this.moreFormData);
            }
            this.importVisible = true;
           
            var obj = document.getElementById('bbq_file');
            if(obj)obj.outerHTML = obj.outerHTML;
        },
    }
};
</script>
<style lang="less">

</style>
